package gonz.common.config;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class GrabLinks {
    private static final String FILE_NAME = "grab_links.properties";
    private Configuration configuration;

    GrabLinks() {
        try {
            configuration = new PropertiesConfiguration(FILE_NAME);
        } catch (ConfigurationException e) {
            throw new RuntimeException("Can't create configuration for " + FILE_NAME, e);

        }
    }

    public List<GrabLink> getGrabLinks() {
        List linkList = configuration.getList(GrabLinksKey.LINK.toString().toLowerCase());
        List toList = configuration.getList(GrabLinksKey.TO.toString().toLowerCase());
        List typeList = configuration.getList(GrabLinksKey.TYPE.toString().toLowerCase());
        if (linkList.size() != toList.size() || linkList.size() != typeList.size()) {
            throw new RuntimeException("In file " + FILE_NAME + " number of \"" +
                    GrabLinksKey.LINK + "\", " +
                    GrabLinksKey.TO + "\" and \"" +
                    GrabLinksKey.TYPE + "\" elements must be equal.");
        }
        List<GrabLink> result = new ArrayList<GrabLink>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HHmmss");
        String defaultTo = sdf.format(new Date(System.currentTimeMillis()));
        for (int i = 0; i < linkList.size(); i++) {
            String link = (String) linkList.get(i);
            String to = (String) toList.get(i);
            String type = (String) typeList.get(i);
            if (StringUtils.isEmpty(to)) {
                to = defaultTo + "_" + i;
            }
            result.add(new GrabLink(link, to, type));

        }
        return result;
    }
}
